//
// Created by Administrator on 2023/7/27.
//
#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <algorithm>

using namespace std;

class Solution {
public:
    int maximumNumberOfStringPairs(vector<string> &words) {
        int ans = 0;
        for (int i = 0; i < words.size(); ++i) {
            for (int j = i + 1; j < words.size(); ++j) {
                if (words[i][0] == words[j][1] and words[i][1] == words[j][0]) {
                    ans++;
                }
            }
        }
        return ans;


    }
};

class Solution2 {
public:
    int maximumNumberOfStringPairs(vector<string> &words) {
        // 保存前面出现过的字符串  查询快一点
        unordered_set<string> st;
        int ans = 0;
        for (auto &s: words) {
            auto r = s;
            reverse(r.begin(), r.end());
            // 看前面是否出现过可以匹配的string
            if (st.count(r)) ans++;
            st.insert(s);
        }
        return ans;
    }
};

int main() {
    vector<string> words{"cd", "ac", "dc", "ca", "zz"};
    Solution2 s;
    cout << s.maximumNumberOfStringPairs(words) << endl;
}